import { Applet } from "@/api/interface/iot";
import {
	addAppletConfig,
	delAppletConfig,
	getAppletConfigList,
	modAppletConfig,
	readAppletConfig,
	saveAppletConfig,
	upgradeConfig
} from "@/api/modules/applet/appletConfig";
import DialogBox from "@/components/DialogBox";
import Empty from "@/components/Empty";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import LazyUploadFile from "@/components/Upload/LazyUploadFile.vue";
import { MessageType } from "@/enums/messageEnum";
import { formatSize } from "@/utils/format";
import mittBus from "@/utils/mittBus";
import { confirm, showMsg, showTips } from "@/utils/util";
import { ElForm } from "element-plus";
import { ComponentInternalInstance, getCurrentInstance, PropType } from "vue";
import "../detail.scss";

export default defineComponent({
	props: {
		btns: {
			type: Array,
			default() {
				return [];
			}
		},
		nodeSn: String,
		detail: {
			type: Object as PropType<Applet.ResUserApplet>,
			default: () => {}
		}
	},
	emits: ["change"],
	setup(props) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		// const btnList = ref([{ menuName: "添加配置", path: "add", btnClass: "primary" }]);
		// 表格配置项
		let columns: ColumnProps[] = [
			{ prop: "name", label: proxy?.$t("appletconfig.tablist_label.name") },
			{ prop: "size", label: proxy?.$t("appletconfig.tablist_label.size") },
			{ prop: "path", label: proxy?.$t("appletconfig.tablist_label.path") },
			{ prop: "updateTime", label: proxy?.$t("appletconfig.tablist_label.update_time") },
			{ prop: "op", label: proxy?.$t("appletconfig.tablist_label.operate"), width: 180 }
		];
		const btnList = ref<any[]>([]);
		watchEffect(() => {
			btnList.value = (props.btns || []).filter((item: any) => item.btnGroup == "5");
			columns = columns.map((item: any) => {
				if (item.prop == "op") {
					item.isShow = !!btnList.value.length;
				}
				return item;
			});
		});
		const initParam = reactive({
			appId: props.nodeSn ? props.detail.appId : props.detail.id,
			appInstanceKey: props.nodeSn ? props.detail.appInstanceId.split(".")[0] : "",
			pageSize: 5
		});
		const proTable = ref();
		const dataCallback = (data: any) => {
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current,
				pageSize: data.size
			};
		};

		type FormInstance = InstanceType<typeof ElForm>;
		const uploadEl = ref();
		const formRef = ref<FormInstance>();
		const formRule = reactive({});

		const clickBtn = async (fn: string, row?: any) => {
			let selected = row ? (row.selectList ? row.selectList : [row]) : [];
			switch (fn) {
				case "read":
					let { code, result, message } = await readAppletConfig({ id: selected[0].id });
					if (code == 200) {
						readDialog.title = selected[0].name;
						readDialog.detail.id = selected[0].id;
						readDialog.detail.content = result as string;
						readDialog.visible = true;
					} else {
						showMsg(message, MessageType.warning);
					}
					break;
				case "add":
					detailDialog.visible = true;
					detailDialog.detail = {
						id: "",
						name: "",
						appId: props.nodeSn ? props.detail.appId : props.detail.id,
						path: "config",
						file: null,
						appInstanceKey: props.nodeSn ? props.detail.appInstanceId.split(".")[0] : ""
					};
					break;
				case "mod":
					detailDialog.visible = true;
					detailDialog.detail = { ...row, name: "" };
					break;
				case "del":
					if (!selected.length) {
						showMsg(proxy?.$t("appletconfig.msg.del"), MessageType.warning);
						return;
					}
					confirm({ content: proxy?.$t("appletconfig.confirm.del") }).then(flag => {
						flag && submitDel({ id: selected.map((item: any) => item.id).join(",") });
					});
					break;
				case "update":
					update(selected);
					break;
			}
		};
		const update = async (data: any) => {
			confirm({ content: proxy?.$t("appletconfig.confirm.update") }).then(async flag => {
				if (!flag) {
					return;
				}
				let { code, message } = await upgradeConfig({
					id: data[0].id
				});
				let ok = showTips(code, `升级服务`, message);
				if (ok) {
					proTable.value.reset();
				}
			});
		};
		const detailDialog = reactive({
			visible: false,
			title: proxy?.$t("appletconfig.dialog_title.config"),
			detail: {
				id: "",
				name: "",
				appId: "",
				path: "config",
				file: null,
				appInstanceKey: props.nodeSn ? props.detail.appInstanceId.split(".")[0] : ""
			}
		});
		const submit = async () => {
			detailDialog.detail.file = uploadEl.value.getFile()?.raw;
			if (!detailDialog.detail.file) {
				showMsg(proxy?.$t("appletconfig.msg.file"), false);
				return;
			}
			let api = detailDialog.detail.id ? modAppletConfig : addAppletConfig;
			let res = await api(detailDialog.detail);
			let ok = showTips(res.code, detailDialog.detail.id ? "修改配置" : "添加配置", res.message);
			if (ok) {
				detailDialog.visible = false;
				proTable.value.getTableList();
			}
		};
		const submitDel = async (dataInfo: any) => {
			let res = await delAppletConfig({ ...dataInfo });
			let ok = showTips(res.code, "删除", res.message);
			if (ok) {
				proTable.value.clearSelection();
				proTable.value.reset();
			}
		};
		const readDialog = reactive({
			visible: false,
			title: proxy?.$t("appletconfig.dialog_title.config"),
			detail: { id: "", content: "" }
		});
		const saveConfig = async () => {
			let { code, message } = await saveAppletConfig(readDialog.detail);
			let ok = showTips(code, "修改配置文件", message);
			if (ok) {
				readDialog.visible = false;
			}
		};
		onBeforeMount(() => {
			mittBus.on("refreshAppletDetail", () => {
				proTable.value.reset();
			});
		});
		onBeforeUnmount(() => {
			mittBus.off("refreshAppletDetail");
		});
		return () => {
			return (
				<div class="p-6 shadow mt-4" style="border: 1px solid #eee;">
					<DialogBox
						v-model:visible={readDialog.visible}
						title={readDialog.title}
						width="650px"
						footerLabel={[proxy?.$t("appletconfig.dialog_footerlaber.close"), proxy?.$t("appletconfig.dialog_footerlaber.save")]}
						onConfirm={() => saveConfig()}
					>
						<el-input v-model={readDialog.detail.content} type="textarea" rows="20"></el-input>
					</DialogBox>

					<DialogBox v-model:visible={detailDialog.visible} title={detailDialog.title} width="650px" onConfirm={() => submit()}>
						<el-form model={detailDialog.detail} ref={formRef} rules={formRule} label-width="100px" class="pl-4 pr-10">
							<el-form-item label={proxy?.$t("appletconfig.dialog_label.path")} prop="path">
								<el-input
									v-model={detailDialog.detail.path}
									placeholder={proxy?.$t("appletconfig.placeholder.path")}
									disabled={!!detailDialog.detail.id}
								/>
							</el-form-item>

							<el-form-item label={proxy?.$t("appletconfig.dialog_label.file")} prop="file">
								{detailDialog.detail.name ? (
									<div class="file-info ">
										{detailDialog.detail.name}
										<el-link
											type="primary"
											class="delete-server-file ml-2 leading-3"
											onClick={() => (detailDialog.detail.name = "")}
										>
											{proxy?.$t("appletconfig.link.reupload")}
										</el-link>
									</div>
								) : null}
								<LazyUploadFile
									style={{ display: detailDialog.detail.name ? "none" : "block" }}
									title={proxy?.$t("appletconfig.lazyupload.title")}
									ref={uploadEl}
									showIcon={false}
									v-model:fileUrl={detailDialog.detail.name}
									v-model:fileName={detailDialog.detail.name}
									width="150px"
									height="32px"
									emptyTips={proxy?.$t("appletconfig.lazyupload.emptytips")}
								></LazyUploadFile>
							</el-form-item>
						</el-form>
					</DialogBox>
					<div class="flex items-center justify-between w-full pb-4">
						<div style="line-height:24px">
							<div class="title-left-line"></div>
							<span>{proxy?.$t("appletconfig.tab_title.config")}</span>
						</div>
						<div class="">
							{!props.nodeSn
								? btnList.value
										?.filter((item: any) => item.path != "del")
										.map((item: any) => {
											return (
												<el-button onClick={() => clickBtn(item.path)} type={item.btnClass}>
													<i class={`iconfont ${item.icon}`}></i>
													{item.menuName}
												</el-button>
											);
										})
								: ""}
						</div>
					</div>
					<ProTable
						// height="275px"
						ref={proTable}
						custSearch={false}
						showHeader={false}
						title={proxy?.$t("appletconfig.tab_title.port")}
						columns={columns}
						requestApi={getAppletConfigList}
						initParam={initParam}
						dataCallback={dataCallback}
					>
						{{
							name: (scope: any) => {
								return scope.row.name;
							},
							size: (scope: any) => {
								return formatSize(scope.row.size).full;
							},
							op: (scope: any) => {
								return (
									<>
										{!props.nodeSn ? (
											<>
												<el-link
													type="danger"
													link
													class="iconfont icontrash-2"
													onClick={() => {
														clickBtn("del", scope.row);
													}}
												>
													{proxy?.$t("appletconfig.link.delete")}
												</el-link>
												<el-link
													type="primary"
													link
													class="iconfont iconbx-file"
													onClick={() => {
														clickBtn("mod", scope.row);
													}}
												>
													{proxy?.$t("appletconfig.link.upload")}
												</el-link>
											</>
										) : (
											<el-link
												type="primary"
												link
												class="iconfont iconbx-file"
												onClick={() => {
													clickBtn("update", scope.row);
												}}
											>
												{proxy?.$t("appletconfig.link.upgrade")}
											</el-link>
										)}

										<el-link
											type="primary"
											link
											class="iconfont iconbx-file"
											onClick={() => {
												clickBtn("read", scope.row);
											}}
										>
											{proxy?.$t("appletconfig.link.edit")}
										</el-link>
									</>
								);
							},
							empty: () => {
								return (
									<div>
										<Empty
											onAdd={() => {
												clickBtn("add");
											}}
											showButton={false}
											title={proxy?.$t("appletconfig.empty.title")}
											subtitle={proxy?.$t("appletconfig.empty.subtitle")}
										/>
									</div>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
